import type { NextApiResponse } from 'next';
import { checkRedisConnection, getRedisInfo } from '@/common/database/redis';
import { CacheService } from '@/common/service/cache';
import R from '@/common/type/response';
import { AuthenticatedRequest, withAuth } from '@common/middleware/auth';

export async function handler(req: AuthenticatedRequest, res: NextApiResponse) {
  if (req.method !== 'GET') {
    return R.error(res, '只支持GET请求');
  }

  try {
    // 检查连接状态
    const isConnected = await checkRedisConnection();
    
    if (!isConnected) {
      return R.error(res, 'Redis 连接失败');
    }

    // 获取 Redis 信息
    const info = await getRedisInfo();
    
    // 获取缓存统计
    const stats = await CacheService.getStats();

    const data = {
      connected: isConnected,
      info: info ? 'Redis 信息获取成功' : 'Redis 信息获取失败',
      stats
    };

    R.success(res, data);
  } catch (error: any) {
    console.error('Redis 状态检查错误:', error);
    R.error(res, error.message || 'Redis 状态检查失败');
  }
}

export default withAuth(handler); 